#include "data_store.h"
#include "SQLiteCpp/SQLiteCpp.h"
#include <iostream>
#include <spdlog/spdlog.h>

namespace ai::facial_recognition {

DataStore::DataStore()
{

}

DataStore::~DataStore()
{

}

int DataStore::save_face_feature(std::string face_feature, int face_feature_length)
{
    try
    {
        // Open a database file
        SQLite::Database db(SQLITE_DB_URI, SQLite::OPEN_READWRITE);

        // Begin transaction
        SQLite::Transaction transaction(db);

        std::string sql = "INSERT INTO face_feature(face_feature, face_feature_length) VALUES (";
        sql = sql + "\"" + face_feature + "\","
        + std::to_string(face_feature_length)
        + ")";

        db.exec(sql);

        transaction.commit();

        return 1;
    }
    catch (std::exception & ex)
    {
        std::cout << "save_face_feature occurs exception." << std::endl;
        std::cout << ex.what() << std::endl;
    }
    return 0;
}


std::vector<FaceFeatureInfo> DataStore::get_all_face_features()
{
    std::vector<FaceFeatureInfo> infos;
    try
    {
        // Open a database file
        SQLite::Database db(SQLITE_DB_URI, SQLite::OPEN_READONLY);

        //Compile a SQL query, containing one parameter (index 1)
        SQLite::Statement query(db, "SELECT * FROM face_feature");

        while (query.executeStep())
        {
            FaceFeatureInfo info = {};
            info.face_feature = query.getColumn("face_feature").getString();
            info.face_feature_size = query.getColumn("face_feature_length").getInt();
            info.row_id = query.getColumn("_id").getInt();

            infos.emplace_back(info);
        }
    }
    catch (std::exception& ex)
    {
        spdlog::error(ex.what());
    }

    return infos;
}

} // namespace
